import prisma from "../prisma/index.js";

// 获取题目列表
export const getQuestionsModel = async (type, keyword, skip, pagesize) => {
    try {
        const where = {};
        if (type) {
            where.type = type;
        }
        if (keyword) {
            where.AND = [
                { content: { contains: keyword } }
            ];
        }
        const [data, total] = await Promise.all([
            prisma.question.findMany({
                where,
                skip,
                take: pagesize,
                orderBy: {
                    id: "desc",
                },
            }),
            prisma.question.count({ where })
        ]);
        
        return {
            data,
            total
        };
    } catch (err) {
        throw err;
    }
};

// 通过id从数据库获取单个题目
export const getSingleQuestionModel = async (id) => {
    try {
        const question = await prisma.question.findUnique({
            where: {
                id: id
            }
        });
        return question;
    } catch (err) {
        console.error('获取题目失败:', err);
        throw err;
    }
};

// 添加题目
export const postQuestionModel = async (type, content, options, answer, difficulty, language) => {
    try {
        // 验证必填字段
        if (!type) {
            return {
                code: 1,
                data: null,
                message: '题型不能为空'
            };
        }
        if (!content) {
            return {
                code: 1,
                data: null,
                message: '题目内容不能为空'
            };
        }
        if (!answer) {
            return {
                code: 1,
                data: null,
                message: '答案不能为空'
            };
        }

        // 验证选项
        if (type !== '编程题' && !options) {
            return {
                code: 1,
                data: null,
                message: '非编程题必须提供选项'
            };
        }

        const result = await prisma.question.create({
            data: {
                type,
                content,
                options: options ? JSON.stringify(options) : null,
                answer: answer ? JSON.stringify(answer) : null,
                difficulty: difficulty || 'medium',
                language: language ? JSON.stringify(language.split(',')) : null, // 转为数组再存储
            },
        });

        return {
            code: 0,
            data: result,
            message: '添加题目成功'
        };
    } catch (err) {
        console.error('创建题目失败:', err);
        return {
            code: 1,
            data: null,
            message: err.message || '添加题目失败'
        };
    }
};

// 更新题目
export const updateQuestionModel = async (id, type, content, options, answer, difficulty, language) => {
    try {
        // 构建 data 对象，只包含有值的字段
        const data = {
            type,
            content,
            difficulty,
            language,
        };
        
        if (options !== undefined && options !== "") data.options = typeof options === 'string' ? options : JSON.stringify(options);
        
        if (answer !== undefined && answer !== "") data.answer = data.type ==="单选题"? JSON.stringify(answer):answer;

        return await prisma.question.update({
            where: { id: parseInt(id) },
            data,
        });
    } catch (err) {
        throw err;
    }
};

// 删除题目
export const deleteQuestionModel = async (ids) => {
    try {
        const result = await prisma.question.deleteMany({
            where: {
                id: {
                    in: ids
                }
            }
        });
        return { count: result.count };

    } catch (err) {
        console.error('Delete error:', err); // 打印详细错误
        throw err;
    }
}; 